package com.gamex.findit.controller.api;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.gamex.findit.ResultCode;
import com.gamex.findit.internal.DefaultConfig;
import com.gamex.findit.model.Member;
import com.gamex.findit.model.MemberItem;
import com.gamex.findit.model.MemberSkill;
import com.gamex.findit.service.MemberService;
import com.gamex.findit.service.SkillService;
import com.gamex.findit.service.MemberSkillService;
import com.gamex.findit.service.NoticeService;
import com.gamex.findit.util.CommonUtil;
import com.mysql.jdbc.StringUtils;

@Controller("memberSkill")
public class MemberSkillController {
	
	private static final Logger logger = LoggerFactory.getLogger(MemberSkillController.class);
	
	@Autowired NoticeService noticeService;
	@Autowired SkillService gameSkillService;
	@Autowired MemberSkillService memberSkillService;
	@Autowired MemberService memberService;
	@Autowired DefaultConfig config;
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param userId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/mySkillList.*")
	public ResponseEntity<String> mySkillList( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @RequestParam(value="userId",required=false) String userId) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        
		ModelMap body = new ModelMap();
		MemberSkill Skill = new MemberSkill();
		Skill.setUserId(userId);
		
		if(StringUtils.isNullOrEmpty(userId)){
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			
		}else{
			List<MemberSkill> skills = null;
			try {
				skills = memberSkillService.getMemberSkill(Skill);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
			if(skills != null){
				body.addAttribute(ResultCode.RESULT,ResultCode.RESULT_CODE_SUCCESS);
				body.addAttribute("list", skills);
			}else{
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param skill
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/spendMySkill.*")
	public ResponseEntity<String> deleteMySkill( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @ModelAttribute MemberSkill skill) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
		ModelMap body = new ModelMap();
		MemberSkill memberSkill = null;
		
		if(StringUtils.isNullOrEmpty(skill.getUserId()) || skill.getSkillId() == 0|| skill.getQuantity() == 0) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			
		}else{
			try {
				// 회원 보유 스킬 정보 추출
				memberSkill = memberSkillService.checkMemberSkill(skill.getSkillId(), skill.getUserId());
				
				int minus = (memberSkill.getQuantity() - skill.getQuantity());
				if(minus < 0) minus = 0;
				skill.setQuantity(minus);
				memberSkillService.updateMemberSkill(skill);
				
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param skill
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/buySkill.*")
	public ResponseEntity<String> buySkill( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @ModelAttribute MemberSkill skill) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        MemberSkill memberSkill = null;
		ModelMap body = new ModelMap();
		
		if(StringUtils.isNullOrEmpty(skill.getUserId()) || skill.getSkillId() == 0) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			try {
				memberSkill = memberSkillService.checkMemberSkill(skill.getSkillId(), skill.getUserId());
				
				if(memberSkill == null){
					// 해당 회원이 요청 skill 이 없으면 신규 등록
					memberSkillService.insertMemberSkill(skill);
				}else{
					// 해당 회원이 요청 skill 있으면 quantity 추가
					skill.setQuantity((memberSkill.getQuantity() + skill.getQuantity()));
					memberSkillService.updateMemberSkill(skill);
				}
				
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	
	}
	
	/**
	 * @param session
	 * @param request
	 * @param response
	 * @param model
	 * @param skill
	 * @param member
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/app/member/buySkillAndSpendPoint.*")
	public ResponseEntity<String> buySkillAndSpendPoint( HttpSession session
							, HttpServletRequest request
							, HttpServletResponse response
							, Model model
							, @ModelAttribute MemberSkill skill
							, @ModelAttribute Member member) throws Exception{
		
		HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.add("Content-Type", "application/json; charset=utf-8");
        MemberSkill memberSkill = null;
		ModelMap body = new ModelMap();
		int skillCnt = skill.getQuantity();
		
		if(StringUtils.isNullOrEmpty(skill.getUserId()) || skill.getSkillId() == 0) {
			body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
		}else{
			
				try {
					memberSkill = memberSkillService.checkMemberSkill(skill.getSkillId(), skill.getUserId());
					
					if(memberSkill == null){
						// 해당 회원이 요청 skill 이 없으면 신규 등록
						memberSkillService.insertMemberSkill(skill);
					}else{
						// 해당 회원이 요청 skill 있으면 quantity 추가
						skill.setQuantity((memberSkill.getQuantity() + skillCnt));
						memberSkillService.updateMemberSkill(skill);
					}
				
				// 구매한 아이템 만큼 코인 절감
				member.setOperation("-");
				System.out.println(skill.getPoint() + " : " + skillCnt + " : " + skill.getPoint() * skillCnt);
				member.setPoint(skill.getPoint() * skillCnt);
				memberService.updateMemberNumeric(member);
			
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_SUCCESS);
			} catch (Exception e) {
				body.addAttribute(ResultCode.RESULT, ResultCode.RESULT_CODE_FAIL);
			}
		}
	
	return new ResponseEntity<String>(CommonUtil.toJson(body), responseHeaders, HttpStatus.CREATED);
	
	}
	
}
